<template>
  <div class="navbar">
    <div class="leftContent">
      <router-link to="/workplace" class="brand">
        <img :src="logoSrc" alt="LOGO" />
      </router-link>

      <div class="middleContent">
        <a-menu v-model:selectedKeys="data.current" mode="horizontal" multiple="false">
          <template v-for="item in data.menuPageList" :key="item.path">
            <a-menu-item v-if="topMenuArr.includes(item.path)" @click="openChild(item.path, item)"
              :class="data.current[0] === item.path ? 'active-item' : ''">
              {{ item.z_ch ? $t("menu." + item.z_ch) : item.menuName }}
            </a-menu-item>
          </template>
        </a-menu>
      </div>
    </div>
    <div style="display: flex;align-items: center">
      <div class="isEnableReinsurance" v-if="userInfo.isEnableReinsurance">{{ userInfo.secretSysTitle }}</div>
    <div class="rightContent">
      <a-popover title="主题色" class="ss" overlayClassName="a-tooltip-layout">
        <template #content>
          <theme-card></theme-card>
        </template>
        <div class="iconBox" style="margin-left: 16px">
          <i class="iconfont icon-reskin" style="font-size: 20px"> </i>
        </div>
      </a-popover>
      <div class="iconBox" style="margin-left: 16px" @click="gotoHome">
        <i class="iconfont icon-computer-1" style="font-size: 20px"> </i>
      </div>

      <div class="iconBox" style="margin-left: 16px" @click="goMeilBox">
        <a-tooltip>
          <template #title>消息通知</template>
          <i class="iconfont icon-information" style="font-size: 20px"> </i>
        </a-tooltip>

      </div>
      <div class="iconBox" style="margin-left: 16px">
        <LocalePicker />
      </div>
      <a-select v-model:value="siteId" style="width: 100%" placeholder="请选择" show-search :filter-option="filterOption"
        :options="siteOptions" @change="siteChange" :fieldNames="{
          label: 'siteName',
          value: 'id',
        }"></a-select>
      <a-dropdown style="height: 60px; wigth: 160px">
        <div class="geren">
          <i class="iconfont icon-a-Defaultavatar"></i>
          <!-- <span>{{ userInfo.userName }}</span> -->
        </div>
        <template #overlay>
          <a-menu class="aMenus">

            <a-menu-item>
              <div class="geren">
                <i style="font-size: 32px; color:#00000040" class="iconfont icon-a-Defaultavatar"></i>
                <span class="userName" v-if="userInfo.userName.length >= 5">
                  <a-tooltip :title="userInfo.userName" placement="top">
                    <a-typography :ellipsis="true" class="ellipsis-text">{{ userInfo.userName }}</a-typography>
                  </a-tooltip>
                </span>
                <span class="userName" v-else> {{ userInfo.userName }} </span>
              </div>
            </a-menu-item>


            <a-menu-item>
              <a @click="personalHandle" class="iconfonts">
                <i class="iconfont icon-a-Headpicture"></i>
                <span>个人中心</span>
              </a>
            </a-menu-item>
            <a-menu-item>
              <a @click="passwordHandle" class="iconfonts">
                <i class="iconfont icon-edit"></i>
                <span>修改密码</span>
              </a>
            </a-menu-item>
            <a-menu-item>
              <a @click="doLogout" class="iconfonts">
                <i class="iconfont icon-a-quittuichu"></i>
                <span>退出登录</span>
              </a>
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>

      <!-- <div class="navMenuItem">
        <a-avatar src="https://joeschmoe.io/api/v1/female/random" :size="32" />
      </div> -->
    </div>
    <div class="isEnableReinsurance2" v-if="userInfo.userSecretName">
      <!-- {{userInfo.userSecretName}} -->
      <div class="tips">
        <p v-if="userInfo.userSecretName && userInfo.userSecretName.length <= 2">{{userInfo.userSecretName}}</p>
      <a-tooltip placement="rightBottom" v-else>
        <template #title>{{userInfo.userSecretName}}</template>
          <!-- {{userInfo.userSecretName}} -->
          <p>{{userInfo.userSecretName.substring(0, 2)}}...</p>
      </a-tooltip>
    </div>
    </div>
    </div>
    <personalCenter :isVisible="ispersonalVisible" @handleOk="handleOk" @updateUserInfo="updateUserInfo" @handleCancle="handleCancle"
      v-if="ispersonalVisible"></personalCenter>
    <modifyPassword :isVisible="ispasswordVisible" @handleOk="handleOk" @handleCancle="handleCancle"
      v-if="ispasswordVisible"></modifyPassword>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, onMounted, onBeforeMount, reactive, toRefs, watch } from "vue";
import themeCard from "@/components/theme/themeCard.vue";
import { systemStore } from "@/store/modules/systemStore";
import { useUserStore } from "@/store/modules/user";
import { useTabsViewStore } from "@/store/modules/tabsView";
import getters from "@/store/getters";
import { theme } from "@/assets/theme/theme.json";
import LocalePicker from "@/components/locale-picker/index.vue";
import menuList from "@/router/asyncRouters";
import personalCenter from "./personalCenter.vue";
import modifyPassword from "./modifyPassword.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import { useRouter, useRoute, RouteRecordRaw } from "vue-router";
import { LOGIN_NAME } from "@/router/constant";
import { Modal, message } from "ant-design-vue";
import { useKeepAliveStore } from "@/store/modules/keepAlive";
import { createVNode, nextTick, computed, ref } from "vue";
import router from "@/router";
import { Storage } from "@/utils/Storage";
import request from "@/api/index";
//data
const topMenuArr = ref<string[]>([]);
const router1 = useRouter();
const route = useRoute();
const sysStore = systemStore();
const userStore = useUserStore();
const tabsViewStore = useTabsViewStore();
const userInfo = getters.userInfo();
const keepAliveStore = useKeepAliveStore();

const ispersonalVisible = ref(false);
const ispasswordVisible = ref(false);
const siteOptions = ref<dataSourceType[]>([]);
const siteId = ref(userInfo.siteId);
const siteDomain = ref<string>("");
const siteName = ref();

const data: any = reactive({
  locale: sysStore.currentLocale,
  menuPageList: menuList,
  current: [],
  showSideMenuDrawer: sysStore.showSideMenuDrawer,
});
const logoSrc = ref<any>(
  userInfo.sysHeaderLogo || "../src/assets/icon/svg/workPlaceLogo.svg"
);
//methods
const openChild = async (path: string, item: any) => {
  sysStore.toggleMenuPath(path);
  sessionStorage.selectMenuPath = path;
  if (item && item.redirect) {
    if (router.currentRoute.value.path != item.redirect) {
      router.push({ path: path });
    }
    sessionStorage.itemPath = item.children[0];
  } else {
    sessionStorage.itemPath = "";
  }
  data.current = [path];
};

const setTheme = (val: string) => {
  let themeJson = theme[val];
  const root = document.documentElement;
  for (let item in themeJson) {
    root.style.setProperty(item, themeJson[item]);
  }
};
const filterOption = (input: string, option: any) => {
  return option.siteName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//获取站点列表
const fetchSiteList = async () => {
  const data: {} = {
    // orgId: userInfo.orgId,
    userId: userInfo.userId,
    allPermissions: true,
  };
  siteOptions.value = await request.fetchStationGroupList(data);
  // fetchChannelChannelTree();
};
// 获取站点域名
const getSiteDomain = async () => {
  const data: {} = {
    id: siteId.value,
  };
  siteDomain.value = await request.getSiteDomain(data);
  // fetchChannelChannelTree();
};
const siteChange = async () => {
  siteOptions.value.map((item: any) => {
    if (siteId.value == item.id) {
      siteName.value = item.siteName;
    }
  });
  let params = {
    token: userInfo.token ?? "",
    menues: userInfo.menues,
    userId: userInfo.userId,
    userName: userInfo.userName,
    orgId: userInfo.orgId,
    siteId: siteId.value,
    siteName: siteName.value,
  };
  await userStore.setUser(params);
  nextTick(() => {
    router1.replace("/workplace");
    Storage.remove("selectFullPath");
    Storage.remove("selectPathQuery");
    Storage.remove("selectMenuPath");
    tabsViewStore.closeAllTabs();
  });

  // router1.go(0);

  getSiteDomain();
};

// 退出登录
const doLogout = () => {
  Modal.confirm({
    title: "您确定要退出登录吗？",
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    centered: true,
    onOk: async () => {
      await userStore.logout();
      keepAliveStore.clear();
      // 移除标签页
      // localStorage.clear();
      message.success("成功退出登录");
      await nextTick();
      router.push({
        path: "/login",
      });
    },
  });
};
const handleOk = async () => {
  ispersonalVisible.value = false;
  ispasswordVisible.value = false;
  await userStore.logout();
  keepAliveStore.clear();
  router.push({
    name: LOGIN_NAME,
    query: {
      redirect: route.fullPath || "/",
    },
  });
};
const updateUserInfo = () => {
  ispersonalVisible.value = false;
};

// 打开个人中心弹窗、
const personalHandle = () => {
  ispersonalVisible.value = true;
};
// 取消个人中心弹窗、
const handleCancle = () => {
  ispersonalVisible.value = false;
  ispasswordVisible.value = false;
};
// 打开个人中心弹窗、
const passwordHandle = () => {
  ispasswordVisible.value = true;
};
// 跳转到站内信
const goMeilBox = () => {
  router.push({ path: "/mail/index" });
  sessionStorage.selectMenuPath = "/mail/index";
  sessionStorage.itemPath = "";
};
// 跳转到演示站
const gotoHome = () => {
  window.open(siteDomain.value);
};
// 取消个人中心弹窗、
// const handleCancle = () => {
//   ispersonalVisible.value = false;
// };

watch(
  () => sysStore.selectMenuPath,
  (_val, oldVal) => {
    data.current = [sysStore.selectMenuPath];
  }
);
watch(
  () => userInfo,
  (newVal, oldVal) => {
    logoSrc.value = newVal.sysHeaderLogo;
  },
  { deep: true, immediate: true }
);
watch(
  () => sysStore.showSideMenuDrawer,
  (_val, oldVal) => {
    data.showSideMenuDrawer = _val;
  }
);

watch(
  () => sysStore.currentLocale,
  (_val, oldVal) => {
    data.locale = _val;
  }
);

//获取菜单的侧边栏
const getMenuArr = () => {
  userInfo.menues &&
    userInfo.menues.length &&
    userInfo.menues.forEach((item: dataSourceType) => {
      if (item.routePath) {
        topMenuArr.value.push(item.routePath);
      }
    });
};

onMounted(async () => {
  fetchSiteList();
  getMenuArr();
  (await sessionStorage.themeName) ? setTheme(sessionStorage.themeName) : "";
  (await sessionStorage.selectMenuPath)
    ? openChild(sessionStorage.selectMenuPath, sessionStorage.itemPath)
    : (data.current = ["/workplace"]);
  getSiteDomain();
});
</script>

<style lang="less" scoped>
.navbar {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: row;
  height: 60px;

  .leftContent {
    display: flex;
  }

  .middleContent {
    min-width: 550px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-direction: row;

    ul {
      width: 100%;
    }
  }
  .isEnableReinsurance {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 9px;
    padding: 0 8px;
    height: 22px;
    font-size: 12px;
    font-weight: 400;
      text-align: center;
      color: rgba(0,0,0,0.85);
      background: rgba(0,0,0,0.02);
      border-radius: 2px 2px 2px 2px;
      border: 1px solid rgba(0,0,0,0.15);
    }
    .isEnableReinsurance2 {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 24px;
    margin-left: -16px;
    padding: 0 8px;
    height: 22px;
    font-size: 12px;
    font-weight: 400;
      text-align: center;
      color: rgba(0,0,0,0.85);
      background: rgba(0,0,0,0.02);
      border-radius: 2px 2px 2px 2px;
      border: 1px solid rgba(0,0,0,0.15);
    }

  .rightContent {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    flex-direction: row;
    padding-right: 24px;
    // width: 500px;
    

    .geren {
      display: flex;
      align-items: center;
      height: 60px;

      i {
        font-size: 32px;

        color: rgba(0, 0, 0, 0.25);
      }

      span {
        width: 48px;
        height: 14px;
        font-size: 14px;
        font-family: Inter-Regular, Inter;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
        line-height: 14px;
        margin-left: 8px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .ant-select {
      margin: 0 24px;
    }

    .navMenuItem {
      cursor: pointer;
      padding: 0 24px;
    }

    .inner-box {
      width: 152px;
      background: #ffffff;
      box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05),
        0px 6px 16px 0px rgba(0, 0, 0, 0.08), 0px 3px 6px -4px rgba(0, 0, 0, 0.12);
      border-radius: 2px 2px 2px 2px;
      padding-bottom: 8px;

      .inner-item {
        padding: 8px 8px 0;
        width: 136px;
        height: 40px;

        .inner-text {
          padding-left: 8px;
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }

    .newAdd {
      display: flex;
      align-items: center;

      .newAddText {
        height: 60px;
        margin-left: 4px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: var(--theme_button_bg_color, #1f6ded);
      }
    }

    .showStation {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-left: 8px;
      width: 133px;
      height: 36px;
      padding: 0 8px;

      .showStationText {
        height: 60px;
        font-size: 14px;
        font-family: Inter-Regular, Inter;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .showStation:hover {
      background: rgba(0, 0, 0, 0.04);
    }

    .iconBox {
      // width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .iconBox:hover {
      background: rgba(0, 0, 0, 0.04);
    }
  }

  .brand {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-direction: row;
    text-decoration: none;
    padding-left: 24px;
    // justify-content: center;
    width: 184px;
    // margin-left: 5px;
    font-size: 16px;
    line-height: 16px;
    font-weight: 700;
    transition: all 0.3s, width 0.3s cubic-bezier(0.2, 0, 0, 1) 0s;

    img {
      width: 118px;
      height: auto;
      max-height: 22px;
    }
  }

  .logoImg {
    width: 32px;
    height: 32px;
    border-radius: 50%;
  }
}

::v-deep(.ant-dropdown-menu-item) {
  height: 40px;
  margin: 8px 0;
}

.iconfonts {
  display: flex;
  align-items: center;

  i {
    font-size: 20px;
  }

  span {
    margin-left: 11px;
  }
}

::v-deep(.active-item .ant-menu-title-content) {
  color: #1f6ded;
  position: relative;
  font-weight: 600;
}

::v-deep(.active-item .ant-menu-title-content::after) {
  position: absolute;
  content: "";
  width: 100%;
  height: 2px;
  background-color: #1f6ded;
  top: 27px;
  left: 0;
}

.ant-menu-horizontal:not(.ant-menu-dark):deep(.ant-menu-item, .ant-menu-submenu) {
  padding: 0 8px 0 24px;
}

:deep(.ant-menu-item::after, .ant-menu-submenu::after) {
  right: 8px;
  bottom: 0;
  left: 24px;
}

.ant-menu-horizontal:not(.ant-menu-dark):deep(.ant-menu-item:hover:after) {
  border: none;
}

.ant-menu-horizontal:not(.ant-menu-dark):deep(.ant-menu-item-selected, .ant-menu-submenu-selected) {
  font-weight: 600;
}

.icon-new {
  color: var(--theme_button_bg_color, #1f6ded);
}
.ant-dropdown-menu {
  display: inline-block;
  width: 160px;
  height: 184px;
  padding: 0;
  :deep(.ant-dropdown-menu-item) {
    height: 40px;
    margin: 4px 0;
  }
  :deep(.ant-dropdown-menu-item:nth-child(1)) {
    width: 100%;
    height: 44px;
    cursor: auto;
    .geren {
      display: flex;
      align-items: center;
    }
  }
}
.userName {
  display: inline-block;
  font-size: 14px;
  width: 96px;
  font-weight: 600;
  margin-left: 8px;
  .ellipsis-text {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 显示省略号 */
}
}
:deep(.ant-menu-horizontal) {
  border: none;
}

:deep(.ant-menu) {
  font-size: 16px;
}

:deep(.ant-menu-item::after) {
  transition: none;
  display: none;
}

:deep(.ant-menu-light .ant-menu-item:hover) {
  color: var(--theme_button_bg_color, #1f6ded);
}

:deep(.ant-menu-item-selected .ant-menu-title-content) {
  padding-bottom: 6px;
  transition: border-color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

:deep(.ant-select-focused) {
  .ant-select-selection-item {
    color: rgba(0, 0, 0, 0.25) !important;
  }
}

:deep(.ant-select-dropdown-placement-bottomLeft) {
  top: 64px !important;
}

:deep(.ant-select) {
  // background: red;
}

:deep(.ant-select-selector) {
  border: none !important;
  box-shadow: 0 0 0 0 !important;
  height: 46px !important;
  margin-top: 16px;
  background-color: transparent !important;
  padding: 0 !important;
  width: 123px !important;

  .ant-select-selection-item {
    width: 115px !important;
    // margin-right: 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    // line-height: 32px !important;
  }
}
</style>

<style>
.a-tooltip-layout.ant-popover-placement-bottom {
  top: 64px !important;
}

.ant-popover-title {
  padding: 16px 24px;
  font-size: 14px;
}

.ant-popover-placement-bottom,
.ant-popover-placement-bottomLeft,
.ant-popover-placement-bottomRigh {
  padding-top: 0;
}
</style>
